//
//  ChapterDBService.m
//  readNovels
//
//  Created by wulanzhou on 2017/2/28.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

#import "ChapterDBService.h"
#import "BSQLConfig.h"
#import "BookDBManager.h"
#import "BookChapterService.h"
#import "CatalogDBService.h"

#define kCatalogStartIndexKey      @"kCatalogStartIndexKey"
#define kCatalogEndIndexKey        @"kCatalogEndIndexKey"
#define kBookChapterQueueDomain    "bk.queue.domain"

@interface ChapterDBService()
@property (nonatomic,strong) CatalogDBService *catalogDBService;
@property (nonatomic,strong) ChapterHpple *chapterHpple;
@end

@implementation ChapterDBService

- (CatalogDBService *)catalogDBService {
    
    if (!_catalogDBService) {
        _catalogDBService=[[CatalogDBService alloc] init];
    }
    return _catalogDBService;
}

//下载章节
- (void)downloadChaptersWithBookId:(NSInteger)book_id hpple:(ChapterHpple *)chapterHpple{
    NSArray <Catalog *> *catalogs = [self.catalogDBService getUnFinishedCatalogsWithBookId:book_id];
    [self downloadChapters:catalogs hpple:chapterHpple];
}

//下载章节
- (void)downloadChapters:(NSArray <Catalog *> *)catalogs hpple:(ChapterHpple *)chapterHpple{
    self.chapterHpple = chapterHpple;
    if (catalogs && [catalogs count]>0) {
        
        [self queueDownloadChapter:catalogs sections:[self getCatalogSections:[catalogs count]] sectionIndex:0];
    }else{
        NSLog(@"没有可下载的章节!!!!");
    }
    
}






- (NSArray <Chapter *> *)chapterWithBookId:(NSInteger)book_id{

    return [[BookDBManager shareInstance] queryDBWithModels:[Chapter class] sql:query_book_id_chapter,[NSNumber numberWithInteger:book_id], nil];
}


#pragma mark - DBInterface Methods
- (BOOL)Insert:(Chapter *)chapter{
    
    NSDateFormatter*dateFormat =[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSInteger finishedValue = chapter.finished ? 1 : 0;
    BOOL success=[[BookDBManager shareInstance] updataDBWithSql:insert_chapter_sql,[NSNumber numberWithInteger:chapter.catalog_id],chapter.title,chapter.content,[NSNumber numberWithInteger:finishedValue],[NSNumber numberWithInteger:chapter.sort],chapter.memo,[dateFormat stringFromDate:chapter.ctime],[dateFormat stringFromDate:chapter.mtime], nil];
    
    if (success) {
        NSLog(@"新增章节=(%@)成功!",chapter.title);
    }else{
        NSLog(@"新增章节=(%@)失败!",chapter.title);
    }
    return success;
}

- (BOOL)Update:(Chapter *)chapter{
    
    NSDateFormatter*dateFormat =[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    BOOL success = NO;
    NSInteger finishedValue = chapter.finished ? 1 : 0;
    if (chapter.content&&[chapter.content length] > 0) {
        success = [[BookDBManager shareInstance] updataDBWithSql:update_chapter_content,chapter.content,[NSNumber numberWithInteger:finishedValue],[dateFormat stringFromDate:chapter.mtime],[NSNumber numberWithInteger:chapter.catalog_id], nil];
    }else{
        success = [[BookDBManager shareInstance] updataDBWithSql:update_chapter_status,[NSNumber numberWithInteger:finishedValue],[dateFormat stringFromDate:chapter.mtime],[NSNumber numberWithInteger:chapter.catalog_id], nil];
    }
    
    if (success) {
        NSLog(@"修改章节=(%@)成功!",chapter.title);
    }else{
        NSLog(@"修改章节=(%@)失败!",chapter.title);
    }
    
    return success;

}

- (BOOL)Delete:(id)kId{
   NSInteger primaryKey = [kId integerValue];
    
   return [[BookDBManager shareInstance] updataDBWithSql:delete_chapter_catalog_id,[NSNumber numberWithInteger:primaryKey], nil];
    //delete_chapter_catalog_id
}

- (Chapter *)Entity:(id)catalog_id{

    NSInteger primaryKey = [catalog_id integerValue];
    NSArray *source = [[BookDBManager shareInstance] queryDBWithModels:[Chapter class] sql:query_catalog_id_chapter,[NSNumber numberWithInteger:primaryKey], nil];
    
    if (source && [source count] >0) {
        
        return source[0];
    }
    return nil;
    
}

#pragma mark -私有方法
- (void)queueDownloadChapter:(NSArray <Catalog *> *)catalogs sections:(NSArray *)sections sectionIndex:(NSInteger)section{
    
    __block typeof(self) weakSelf = self;
    
    NSDictionary *dic = sections[section];
    NSInteger start = [[dic objectForKey:kCatalogStartIndexKey] integerValue];
    NSInteger end = [[dic objectForKey:kCatalogEndIndexKey] integerValue];
    [self queueDownloadChapter:catalogs startIndex:start endIndex:end completed:^{
        if (section+1 < [sections count]) {
            [weakSelf queueDownloadChapter:catalogs sections:sections sectionIndex:section+1];
        }else{
            NSLog(@"章节全部下载完成");
        }
    }];
}
- (void)queueDownloadChapter:(NSArray <Catalog *> *)catalogs startIndex:(NSInteger)start endIndex:(NSInteger)end completed:(void(^)())finished{
    
    //__block typeof(self) weakSelf = self;
    //NSString *queue_key = [NSString stringWithFormat:@"%@_%ld",kBookChapterQueueDomain,start];
    dispatch_queue_t queue = dispatch_queue_create(kBookChapterQueueDomain, DISPATCH_QUEUE_CONCURRENT);
    for (NSInteger i=start; i<=end; i++) {
        
        Catalog *book = catalogs[i];
        BookChapterService *chapter = [[BookChapterService alloc] init];
        chapter.catalog = book;
        chapter.chapterHpple = self.chapterHpple;
        chapter.chapterFinishedBlock = ^(BOOL success,NSError * _Nullable error){
            if (success){
                NSLog(@"章节:%@ 下载成功,index=%ld",book.name,(long)i);
            }else{
                NSLog(@"章节:%@ 下载失败,index=%ld",book.name,(long)i);
            }
            if (i == end) { //表示下载完成
                NSLog(@"索引%ld-%ld结束队列",(long)start,(long)end);
                if (finished) {
                    finished();
                }
            }
        };
        
        dispatch_async(queue, ^{
            [chapter asyncChapter];
        });
        
    }
    
}
- (void)downloadSingleChapter:(Catalog *)book{
    
    BookChapterService *chapter = [[BookChapterService alloc] init];
    chapter.catalog = book;
    chapter.chapterHpple = self.chapterHpple;
    chapter.chapterFinishedBlock = ^(BOOL success,NSError * _Nullable error){
        if (success) {
            NSLog(@"章节:%@ 下载成功,index=%ld",book.name,book.sort);
        }else{
             NSLog(@"章节:%@ 下载失败,index=%ld",book.name,book.sort);
        }
    };
    [chapter asyncChapter];

}
- (NSArray *)getCatalogSections:(NSInteger )total{
    
    NSInteger num = 20;
    
    NSMutableArray *sections = [NSMutableArray arrayWithCapacity:0];
    NSInteger len = total % num == 0 ? (total / num) : (total / num)+1;
    
    for (NSInteger i = 0; i< len; i++) {
        NSInteger start = i*num;
        NSInteger end = (i+1)*num-1;
        if (end >=total) {
            end = total - 1;
        }
        
        [sections addObject:@{kCatalogStartIndexKey:[NSNumber numberWithInteger:start],kCatalogEndIndexKey:[NSNumber numberWithInteger:end]}];
    }
    
    return sections;
}


@end
